from apps.system.rank.dao import RankDao
from decimal import Decimal
from apps.user.dao import UserDao
from apps.pay.recordIncomes.dao import RecordIncomesDao
from apps.pay.order.countAward.levelAward import countLevelAward

# 发放见点奖

def countGradeAward(key, order, by, awardType):
    print('计算间点奖', key, order, by, awardType)
    _user = UserDao().findOneByObjId(order.user.id)
    _ranks = RankDao().findAll().filter(rankType=key).order_by('grade')

    lastRank = _ranks.first()
    if _user.parent:
        _parent = UserDao().findOneByObjId(_user.parent.id)
        while 1:
            if _parent:
                _parentRank = _parent.rank
                print('计算用户', _parent.id, _parentRank.grade)
                if not _parentRank:
                    _parent = _parent.parent
                    continue
                if _parentRank.grade == 0:
                    _parent = _parent.parent
                    continue
                
                for rank in _ranks:
                    if _parentRank.grade == rank.grade and rank.grade > lastRank.grade:
                        print('满足条件计算奖励', _parent.id, rank.grade)
                        m = 0
                        n = 0
                        if by == 'money':
                            if rank.gradeAward <= 0:
                                print('奖金未设置，不予发放')
                                continue
                            m = rank.gradeAward
                            n = lastRank.gradeAward
                        elif by == 'rate':
                            if rank.gradeAwardRate <= 0:
                                print('奖金比例未设置，不予发放')
                                return
                            m = order.realPay * rank.gradeAwardRate
                            n = order.realPay * lastRank.gradeAwardRate
                        award = (Decimal(m)-Decimal(n)).quantize(Decimal("0.00"))
                        addAward(awardType, _parent, award, order)
                        # 计算平级奖励
                        if rank.isLevelAward:
                            countLevelAward(_parent, award, order, rank, key)
                        lastRank = rank
                        break
                _parent = _parent.parent
                print('_parent', _parent)
            else:
                print('上级不存在')
                break
    else:
        print('上级不存在')

# 增加见点奖
def addAward(awardType, _parent, award, order):
    print('发放间点奖', award)
    UserDao().addWallet('incomes', _parent, award)
    UserDao().addWallet('historyIncomes', _parent, award)
    # 新增钱包记录
    data = {}
    data['scene'] = awardType#'gradeAward'
    data['user'] = _parent.id
    data['fromUser'] = order.user.id
    data['orderId'] = order.orderId
    data['money'] = Decimal(award).quantize(Decimal("0.00"))
    data['payway'] = 'incomes'
    data['changeWay'] = 'add'
    RecordIncomesDao().create(data)